package com.atguigu.gmall.item.config;


import com.atguigu.gmall.common.cache.GmallCacheAspect;
import com.atguigu.gmall.common.config.ItemServiceRedissonConfig;
import com.atguigu.gmall.common.config.RedissonConfig;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.*;
import java.util.logging.Logger;


/**
 * 工具类提取的所有自动配置类使用 @Import 即可
 * 导入自己的GmallCacheAspect.class 分布式缓存切面
 */
@EnableAspectJAutoProxy //开启切面功能
@Import({ItemServiceRedissonConfig.class, GmallCacheAspect.class})
//让Spring Boot自己的RedisAutoConfiguration 配置完以后再启动redisson需要配置@AutoConfigureAfter
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Configuration //加上这个注解，主启动类就会加载这个配置
public class ItemConfig {

    /*@Bean
    Logger.Level feignLoggerLevel(){

    }*/

    //配置自己的业务线程池，核心业务线程池
    @Bean("corePool")
    public ThreadPoolExecutor executor(ThreadConfigProperties properties){
       return new ThreadPoolExecutor(properties.core,
                properties.max,
                properties.keepalive, //线程池 1分钟了都没有活要干
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(properties.queueLength), //阻塞队列 10000人排队
                Executors.defaultThreadFactory(), //线程工厂
                new ThreadPoolExecutor.AbortPolicy()); //拒绝队列
    }

    @Component
    @ConfigurationProperties(prefix = "item-service.thread")
    @Data
    class ThreadConfigProperties{
       private Integer core;
       private Integer max;
       private Long keepalive;
       private Integer queueLength;
    }

    class MyItemServiceThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("item-service: " + UUID.randomUUID().toString().substring(0, 5));
            return thread;
        }
    }
}
